package com.eastfair.venuebooking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.venuebooking.dao.SpaceCategoryMapper;
import com.eastfair.venuebooking.dao.SpaceMapper;
import com.eastfair.venuebooking.dao.SpacePriceUnitMapper;
import com.eastfair.venuebooking.dto.SalesAnalysisDTO;
import com.eastfair.venuebooking.dto.SpacePageQuery;
import com.eastfair.venuebooking.dto.SpaceSaveDTO;
import com.eastfair.venuebooking.dto.SpaceUpdateDTO;
import com.eastfair.venuebooking.entity.PriceListSpace;
import com.eastfair.venuebooking.entity.Space;
import com.eastfair.venuebooking.entity.SpaceCategory;
import com.eastfair.venuebooking.entity.SpacePriceUnit;
import com.eastfair.venuebooking.enums.SpacePriceUnitCodeEnum;
import com.eastfair.venuebooking.enums.VenueBookingMoudleEnum;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.PriceListSpaceService;
import com.eastfair.venuebooking.service.SpaceCategoryService;
import com.eastfair.venuebooking.service.SpacePriceUnitService;
import com.eastfair.venuebooking.service.SpaceService;
import com.eastfair.venuebooking.vo.SpacePriceUnitVO;
import com.eastfair.venuebooking.vo.SpaceVO;
import com.eastfair.venueservice.entity.CreatCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * 业务实现类
 * 场地表
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class SpaceServiceImpl extends SuperServiceImpl<SpaceMapper, Space> implements SpaceService {
    public static final String SP = "SP";
    public static final String SPACE_CODE = "space_code";

    @Autowired
    private SpaceMapper spaceMapper;
    @Autowired
    private SpacePriceUnitMapper spacePriceUnitMapper;
    @Resource
    private SpacePriceUnitService spacePriceUnitService;

    @Autowired
    private AttachmentFileFeign attachmentFileFeign;

    @Resource
    private SpaceCategoryService spaceCategoryService;

    @Autowired
    private SpaceCategoryMapper spaceCategoryMapper;

    @Autowired
    private PriceListSpaceService priceListSpaceService;

    @Override
    protected R<Boolean> handlerSave(Space model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerUpdateById(Space model) {
        model.setSyncState(BusinessConstant.NO);
        return R.successDef();
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Space> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    /**
     * 查询展厅列表
     *
     * @param params
     * @return
     */
    @Override
    public IPage<SpaceVO> querySpaceList(PageParams<SpacePageQuery> params) {
        log.info("SpaceServiceImpl +++++ pageCustomerMain - 分页查询展厅列表 params={}", JSONObject.toJSON(params));
        handlerQueryParams(params);
        Page<Space> page = params.buildPage();

        SpacePageQuery spacePageQuery = params.getModel();

        //查询展厅列表
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Space::getIsDeleted, BusinessConstant.DELETE_NO)
                .like(StrUtil.isNotBlank(spacePageQuery.getSpaceName()),
                        Space::getSpaceName, spacePageQuery.getSpaceName())
                .eq(Objects.nonNull(spacePageQuery.getSpaceCategoryId()),
                        Space::getSpaceCategoryId, spacePageQuery.getSpaceCategoryId())
                .orderByAsc(Space::getSort)
                .orderByDesc(Space::getCreateTime);
        page = page(page, queryWrapper);
        List<Space> records = page.getRecords();
        Page<SpaceVO> resultPage = ConvertUtil.convertPage(page, SpaceVO.class);
        //遍历查询展厅的场地计价
        for (SpaceVO spaceVO : resultPage.getRecords()) {
            SpaceCategory spaceCategory = spaceCategoryMapper.selectById(spaceVO.getSpaceCategoryId());
            if (Objects.nonNull(spaceCategory)) {
                spaceVO.setCategoryName(spaceCategory.getCategoryName());
            }
            //获取图片数量
            AttachmentFileDTO attachmentFileDTO = new AttachmentFileDTO();
            attachmentFileDTO.setBusinessId(spaceVO.getId());
            attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.SPACE_DRAWING.getCode());
            R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(attachmentFileDTO);
            spaceVO.setAttachmentCount(listR.getData().size());
            //修改图片数量
            Space space = new Space();
            space.setId(spaceVO.getId());
            space.setAttachmentCount(listR.getData().size());
            int i = spaceMapper.updateById(space);
            //查询展厅下的展厅计价数据
            List<SpacePriceUnit> spacePriceUnitList = spacePriceUnitMapper.selectBySpaceId(spaceVO.getId());
            List<SpacePriceUnitVO> spacePriceUnitVOList = ConvertUtil.convertList(spacePriceUnitList, SpacePriceUnitVO.class);
            spaceVO.setSpacePriceUnitVOList(spacePriceUnitVOList);
        }
        return resultPage;
    }

    @Override
    public List<String> listTags() {
        List<String> tags = spaceMapper.listTags();
        if (tags == null || tags.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> rawTags = new ArrayList<>(16);
        tags.forEach(tag -> CollectionUtil.addAll(rawTags, StrUtil.split(tag, ",")));
        return rawTags;
    }

    @Override
    public SpaceVO getBySpaceName(String spaceName) {
        log.info("getBySpaceName - 展厅名称查询展厅, spaceName={}", spaceName);
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(Space::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(StrUtil.isNotBlank(spaceName), Space::getSpaceName, spaceName)
        ;
        List<Space> list = list(queryWrapper);
        if (list == null || list.isEmpty()) {
            return null;
        }
        Space space = list.get(0);
        return BeanUtil.toBean(space, SpaceVO.class);
    }

    /**
     * 添加展厅信息
     *
     * @param spaceSaveDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSpaceInfo(SpaceSaveDTO spaceSaveDTO) {
        log.info("SpaceServiceImpl +++++ saveSpaceInfo - 添加展厅信息 spaceSaveDTO={}", JSONObject.toJSON(spaceSaveDTO));
        spaceSaveDTO.setSpaceCode(CreatCode.creatCode(spaceMapper, SPACE_CODE, 5, SP));
        Space space = BeanUtil.toBean(spaceSaveDTO, Space.class);
        boolean save = save(space);
        List<SpacePriceUnit> spacePriceUnitList = spaceSaveDTO.getSpacePriceUnitList();
        //判断场地计价方式是否为空
        if (Objects.isNull(spacePriceUnitList) || spacePriceUnitList.size() == 0) {
            throw BizException.wrap(VenueBookingExceptionCode.SP_NOT_UNIT);
        }
        spacePriceUnitList.forEach((s) -> {
            s.setSpaceId(space.getId());
            s.setIsDeleted(0);
            s.setIsEnabled(1);
        });
        //添加展厅计价方式
        spacePriceUnitMapper.insertBatchSomeColumn(spaceSaveDTO.getSpacePriceUnitList());
        log.info("SpaceServiceImpl +++++ insertBatchSomeColumn -》》》》 添加展厅计价方式成功");
        //展厅附件集合
        List<AttachmentFileDTO> attachmentFileDTOList = spaceSaveDTO.getAttachmentFileDTOList();
        if (Objects.nonNull(attachmentFileDTOList) && attachmentFileDTOList.size() > 0) {
            attachmentFileDTOList.forEach((s) -> {
                s.setBusinessId(space.getId());
                s.setBusinessType(VenueBookingMoudleEnum.SPACE_DRAWING.getCode());
            });
            //添加展厅图纸附件
            attachmentFileFeign.addAttachmentFile(attachmentFileDTOList);
            log.info("SpaceServiceImpl +++++ saveOrUpdateAttachmentFile -》》》》 添加展厅图纸附件成功");
        }

        if (Boolean.TRUE.equals(save)) {
            log.info("SpaceServiceImpl +++++ saveSpaceInfo -》》》》 添加展厅信息成功");
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<SpaceSaveDTO> list) {
        log.info("saveBatch - 批量保存场地, list={}", list);
        if (list == null || list.isEmpty()) {
            return false;
        }
        list.forEach(this::saveSpaceInfo);
        return true;
    }

    /**
     * 修改展厅信息
     *
     * @param spaceUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSpaceInfo(SpaceUpdateDTO spaceUpdateDTO) {
        log.info("SpaceServiceImpl +++++ updateSpaceInfo - 修改展厅信息 spaceUpdateDTO={}", JSONObject.toJSON(spaceUpdateDTO));
        Boolean flag = Boolean.FALSE;
        List<SpacePriceUnit> spacePriceUnitList = spaceUpdateDTO.getSpacePriceUnitList();
        //判断场地计价方式是否为空
        if (Objects.isNull(spacePriceUnitList) || spacePriceUnitList.size() == 0) {
            throw BizException.wrap(VenueBookingExceptionCode.SP_NOT_UNIT);
        }
        spacePriceUnitList.forEach((s) -> s.setSpaceId(spaceUpdateDTO.getId()));

        //修改展厅计价方式
        spacePriceUnitList.forEach((s) -> {
            if(Objects.nonNull(s.getId())){
                spacePriceUnitMapper.updateById(s);
            }else {
                spacePriceUnitService.save(s);
            }
        });
        log.info("SpaceServiceImpl +++++ updateBatchByIds -》》》》 修改展厅计价方式成功");

        // spacePriceUnitMapper.updateBatchByIds(spaceUpdateDTO.getSpacePriceUnitList());
        List<AttachmentFileDTO> attachmentFileDTOList = spaceUpdateDTO.getAttachmentFileDTOList();
        //删除展厅图纸附件
        AttachmentFileDTO attachmentFileDTO = new AttachmentFileDTO();
        attachmentFileDTO.setBusinessId(spaceUpdateDTO.getId());
        R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(attachmentFileDTO);
        if (Objects.nonNull(listR) && Objects.nonNull(listR.getData()) && listR.getData().size() > 0) {
            listR.getData().forEach((s) -> {
                attachmentFileFeign.detele(s.getId());
            });
        }
        //修改展厅图纸附件
        if (Objects.nonNull(attachmentFileDTOList) && attachmentFileDTOList.size() > 0) {
            attachmentFileDTOList.forEach((s) -> {
                s.setBusinessId(spaceUpdateDTO.getId());
                s.setBusinessType(VenueBookingMoudleEnum.SPACE_DRAWING.getCode());
            });
            //修改展厅图纸附件
            attachmentFileFeign.addAttachmentFile(attachmentFileDTOList);
            log.info("SpaceServiceImpl +++++ saveOrUpdateAttachmentFile -》》》》 修改展厅图纸附件成功");
        }

        Space space = BeanUtil.toBean(spaceUpdateDTO, Space.class);
        int i = spaceMapper.updateById(space);
        if (i > 0) {
            flag = Boolean.TRUE;
            log.info("SpaceServiceImpl +++++ updateSpaceInfo -》》》》 修改展厅信息成功");
        }
        return flag;
    }

    /**
     * 逻辑删除展厅信息
     *
     * @param spaceUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delSpaceInfoById(SpaceUpdateDTO spaceUpdateDTO) {
        log.info("SpaceServiceImpl +++++ delSpaceInfoById - 逻辑删除展厅信息 spaceUpdateDTO={}", JSONObject.toJSON(spaceUpdateDTO));
        //查询展厅是否已被价目表引用
        List<PriceListSpace> list = priceListSpaceService.list(new QueryWrapper<PriceListSpace>().lambda()
                .eq(PriceListSpace::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(PriceListSpace::getSpaceId, spaceUpdateDTO.getId()));
        if (Objects.nonNull(list) && list.size() > 0) {
            throw BizException.wrap(VenueBookingExceptionCode.NOT_DEL_SPACE);
        }
        spaceUpdateDTO.setIsDeleted(1);
        Space space = BeanUtil.copyProperties(spaceUpdateDTO, Space.class);
        //删除展厅计价方式数据
        spacePriceUnitMapper.delBySpaceId(spaceUpdateDTO.getId());
        log.info("SpaceServiceImpl +++++ delBySpaceId -》》》》 逻辑删除展厅计价方式成功");
        Boolean flag = this.updateById(space);
        if (Boolean.TRUE.equals(flag)) {
            log.info("SpaceServiceImpl +++++ delSpaceInfoById -》》》》 逻辑删除展厅信息成功");
        }

        return flag;
    }

    /**
     * 展厅详情信息
     *
     * @param id
     * @return
     */
    @Override
    public SpaceVO getSpaceById(Long id) {
        //获取展厅基础信息
        Space space = this.getById(id);
        SpaceVO spaceVO = BeanUtil.copyProperties(space, SpaceVO.class);
        //查询展厅计价方式
        List<SpacePriceUnit> spacePriceUnitList = spacePriceUnitMapper.selectBySpaceId(spaceVO.getId());
        List<SpacePriceUnitVO> spacePriceUnitVOList = ConvertUtil.convertList(spacePriceUnitList, SpacePriceUnitVO.class);
        //获取展厅计价方式
        spaceVO.setSpacePriceUnitVOList(spacePriceUnitVOList);
        AttachmentFileDTO attachmentFileDTO = new AttachmentFileDTO();
        attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.SPACE_DRAWING.getCode());
        attachmentFileDTO.setBusinessId(id);
        //查询展厅下的附件数据
        R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(attachmentFileDTO);
        // List<AttachmentFileDTO> attachmentFileDTOS = ConvertUtil.convertList(listR.getData(),AttachmentFileDTO.class);
        //获取附件数据
        spaceVO.setAttachmentFileVOList(listR.getData());
        return spaceVO;
    }

    @Override
    public Boolean syncCallback(List<Long> ids) {
        return update(new UpdateWrapper<Space>().lambda()
                .set(Space::getSyncState, BusinessConstant.YES)
                .in(Space::getId, ids));
    }

    @Override
    public List<SpaceVO> queryNeedSyncSpace() {
        List<Space> list = list(new QueryWrapper<Space>().lambda().eq(Space::getSyncState, BusinessConstant.NO));
        List<SpaceVO> spaceVOS = new ArrayList<>(8);
        for (Space space : list) {
            SpaceVO spaceVO = BeanUtil.copyProperties(space, SpaceVO.class);
            spaceVOS.add(spaceVO);
        }
        return spaceVOS;
    }

    /**
     * 获取有效展厅列表
     *
     * @return
     */
    @Override
    public List<Space> getSpaceList(SalesAnalysisDTO salesAnalysisDTO) {
        //查询展厅列表
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Space::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(Objects.nonNull(salesAnalysisDTO.getSpaceId()), Space::getId, salesAnalysisDTO.getSpaceId());
        List<Space> list = list(queryWrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importSpace(MultipartFile file) throws IOException {
        log.info("importSpace - 导入展厅");
        if (file == null) {
            throw BizException.wrap(1001, "未上传文件");
        }
        ExcelReader reader;
        try (InputStream inputStream = file.getInputStream()) {
            reader = ExcelUtil.getReader(inputStream);
        }
        List<Map<String, Object>> importList = reader.readAll();
        if (importList == null || importList.isEmpty()) {
            throw BizException.wrap(-1, "读取数据为空");
        }
        List<SpaceSaveDTO> spaceSaveDTOList = new ArrayList<>();
        List<String> spaceNameList = new ArrayList<>();
        for (int i = 0; i < importList.size(); i++) {
            int rowIndex = i + 2;
            Map<String, Object> map = importList.get(i);
            SpaceSaveDTO spaceSaveDTO = new SpaceSaveDTO();
            List<SpacePriceUnit> spacePriceUnitList = new ArrayList<>();
            // 展厅名称
            Object spaceNameObj = map.get("展厅名称");
            if (ObjectUtils.isEmpty(spaceNameObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，展厅名称为空");
            }
            String spaceName = StrUtil.trim((String) spaceNameObj);
            spaceSaveDTO.setSpaceName(spaceName);
            // 展厅分类
            Object spaceCategoryObj = map.get("所属类型");
            if (ObjectUtils.isEmpty(spaceCategoryObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，所属类型为空");
            }
            String spaceCategory = StrUtil.trim((String) spaceCategoryObj);
            spaceSaveDTO.setSpaceCategoryName(spaceCategory);
            spaceNameList.add(spaceCategory);
            // 场地保证金
            Object spaceDepositObj = map.get("场地保证金");
            if (ObjectUtils.isEmpty(spaceDepositObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，场地保证金为空");
            }
            Double spaceDeposit = (Double) spaceDepositObj;
            BigDecimal spaceDepositDecimal = BigDecimal.valueOf(spaceDeposit).setScale(2, RoundingMode.DOWN);
            spaceSaveDTO.setSpaceDeposit(spaceDepositDecimal);
            // 服务预付款
            Object serviceAdvanceChargeObj = map.get("服务预存款");
            if (ObjectUtils.isEmpty(serviceAdvanceChargeObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，服务预存款为空");
            }
            Double serviceAdvanceCharge = (Double) serviceAdvanceChargeObj;
            BigDecimal serviceAdvanceChargeDecimal = BigDecimal.valueOf(serviceAdvanceCharge).setScale(2, RoundingMode.DOWN);
            spaceSaveDTO.setServiceAdvanceCharge(serviceAdvanceChargeDecimal);
            // 计价面积
            Object priceAreaObj = map.get("计价面积");
            if (ObjectUtils.isEmpty(priceAreaObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，计价面积为空");
            }
            Double priceArea = (Double) priceAreaObj;
            spaceSaveDTO.setPriceArea(priceArea);
            // 建筑面积
            Object buildAreaObj = map.get("建筑面积");
            if (ObjectUtils.isEmpty(buildAreaObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，建筑面积为空");
            }
            Double buildArea = (Double) buildAreaObj;
            spaceSaveDTO.setBuildArea(buildArea);
            // 排序
            Object sortObj = map.get("排序");
            if (ObjectUtils.isEmpty(sortObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，排序为空");
            }
            Long sort = (Long) sortObj;
            spaceSaveDTO.setSort(sort.intValue());
            // 平米/天
            Object squareMeterPerDayObj = map.get("平米/天");
            if (ObjectUtils.isEmpty(squareMeterPerDayObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，平米/天为空");
            }
            Double squareMeterPerDay = (Double) squareMeterPerDayObj;
            BigDecimal squareMeterPerDayBigDecimal = BigDecimal.valueOf(squareMeterPerDay).setScale(2, RoundingMode.DOWN);
            SpacePriceUnit squareMeterPerDaySpacePriceUnit = new SpacePriceUnit();
            squareMeterPerDaySpacePriceUnit.setUnitCode(SpacePriceUnitCodeEnum.SQUARE_METER_PER_DAY.getCode());
            squareMeterPerDaySpacePriceUnit.setPrice(squareMeterPerDayBigDecimal);
            spacePriceUnitList.add(squareMeterPerDaySpacePriceUnit);
            // 平米/小时
            Object squareMeterPerHourObj = map.get("平米/小时");
            if (ObjectUtils.isEmpty(squareMeterPerHourObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，平米/小时为空");
            }
            Double squareMeterPerHour = (Double) squareMeterPerHourObj;
            BigDecimal squareMeterPerHourBigDecimal = BigDecimal.valueOf(squareMeterPerHour).setScale(2, RoundingMode.DOWN);
            SpacePriceUnit squareMeterPerHourSpacePriceUnit = new SpacePriceUnit();
            squareMeterPerHourSpacePriceUnit.setUnitCode(SpacePriceUnitCodeEnum.SQUARE_METER_PER_HOUR.getCode());
            squareMeterPerHourSpacePriceUnit.setPrice(squareMeterPerHourBigDecimal);
            spacePriceUnitList.add(squareMeterPerHourSpacePriceUnit);
            // 每小时
            Object perHourObj = map.get("每小时");
            if (ObjectUtils.isEmpty(perHourObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，每小时为空");
            }
            Double perHour = (Double) perHourObj;
            BigDecimal perHourBigDecimal = BigDecimal.valueOf(perHour).setScale(2, RoundingMode.DOWN);
            SpacePriceUnit perHourSpacePriceUnit = new SpacePriceUnit();
            perHourSpacePriceUnit.setUnitCode(SpacePriceUnitCodeEnum.PER_HOUR.getCode());
            perHourSpacePriceUnit.setPrice(perHourBigDecimal);
            spacePriceUnitList.add(perHourSpacePriceUnit);
            // 每天
            Object perDayObj = map.get("每天");
            if (ObjectUtils.isEmpty(perDayObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，每天为空");
            }
            Double perDay = (Double) perDayObj;
            BigDecimal perDayBigDecimal = BigDecimal.valueOf(perDay).setScale(2, RoundingMode.DOWN);
            SpacePriceUnit perDaySpacePriceUnit = new SpacePriceUnit();
            perDaySpacePriceUnit.setUnitCode(SpacePriceUnitCodeEnum.PER_DAY.getCode());
            perDaySpacePriceUnit.setPrice(perDayBigDecimal);
            spacePriceUnitList.add(perDaySpacePriceUnit);
            // 半天
            Object halfDayObj = map.get("半天");
            if (ObjectUtils.isEmpty(halfDayObj)) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，半天为空");
            }
            Double halfDay = (Double) halfDayObj;
            BigDecimal halfDayBigDecimal = BigDecimal.valueOf(halfDay).setScale(2, RoundingMode.DOWN);
            SpacePriceUnit halfDaySpacePriceUnit = new SpacePriceUnit();
            halfDaySpacePriceUnit.setUnitCode(SpacePriceUnitCodeEnum.HAL_DAY.getCode());
            halfDaySpacePriceUnit.setPrice(halfDayBigDecimal);
            spacePriceUnitList.add(halfDaySpacePriceUnit);

            spaceSaveDTO.setSpacePriceUnitList(spacePriceUnitList);
            spaceSaveDTOList.add(spaceSaveDTO);
        }
        // 查询展厅分类列表
        List<SpaceCategory> spaceCategoryList = spaceCategoryService.listByCategoryNames(spaceNameList);
        Map<String, SpaceCategory> categoryDict = new HashMap<>(16);
        spaceCategoryList.forEach(spaceCategory -> categoryDict.put(spaceCategory.getCategoryName(), spaceCategory));
        for (int i = 0; i < spaceSaveDTOList.size(); i++) {
            int rowIndex = i + 2;
            SpaceSaveDTO spaceSaveDTO = spaceSaveDTOList.get(i);
            // 添加展厅分类ID
            SpaceCategory spaceCategory = categoryDict.get(spaceSaveDTO.getSpaceCategoryName());
            if (spaceCategory == null) {
                throw BizException.wrap(-1, "第" + rowIndex + "行，所属类型在系统中不存在，请检查所属类型名称");
            }
            spaceSaveDTO.setSpaceCategoryId(spaceCategory.getId());
        }
        return saveBatch(spaceSaveDTOList);
    }

    @Override
    public void getImportTemplate(HttpServletResponse response) throws Exception {
        log.info("getImportTemplate - 获取展厅导入模版");
        ClassPathResource resource = new ClassPathResource("template/spaceimport.xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=联系人.xlsx");
        try (InputStream input = resource.getInputStream();
             ServletOutputStream out = response.getOutputStream()) {
            IOUtils.copy(input, out);

            response.flushBuffer();
        } catch (IOException e) {
            throw BizException.wrap(-1, "获取展厅导入模版失败");
        }
    }

    public void handlerQueryParams(PageParams<SpacePageQuery> params) {
        if (StrUtil.isBlank(params.getSort()) || StrUtil.isBlank(params.getOrder())) {
            params.setSort("createTime");
            params.setOrder("descending");
        }
    }
}
